using AutoMapper;
using lwzlz.Application.System.Dto;
using lwzlz.Common;
using lwzlz.Core;
using lwzlz.Core.Repository;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;

namespace lwzlz.Application.System
{
    public class TeacherService
    {
        private readonly IRepository<Teacher> _repository;

        public TeacherService()
        {
            _repository = new Repository<Teacher>();
        }

        #region 查询

        /// <summary>
        /// 获取实体
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public Teacher Get(int id)
        {
            return _repository.Get(id);
        }

        /// <summary>
        /// 获取输出对象
        /// </summary>
        /// <typeparam name="TDto"></typeparam>
        /// <param name="id"></param>
        /// <returns></returns>
        public TDto Get<TDto>(int id) where TDto : class, new()
        {
            var entity = Get(id);
            return Mapper.Map<TDto>(entity);
        }

        /// <summary>
        /// 分页数据
        /// </summary>
        /// <param name="dic_conditions"></param>
        /// <param name="count"></param>
        /// <returns></returns>
        public List<dynamic> GetListPage(
            int pageNumber, int rowsPerPage, Dictionary<string, string> dic_conditions, string field, string order, out int count)
        {
            #region 字段
            var select = @"
                a.*,
                b.Name AS StoreName";
            #endregion

            #region 表
            var table = @"
                    dbo.Ser_Teacher a
                LEFT JOIN dbo.Ser_Store b
                    ON b.Id = a.StoreId";
            #endregion
            #region 参数查询

            string where = " a.IsDeleted=0 ";

            //数据库参数
            Dictionary<string, object> dic = new Dictionary<string, object>();

            //用户名
            if (dic_conditions.ContainsKey("UserName"))
            {
                dic.Add("@UserName", dic_conditions["UserName"]);
                where += " AND a.UserName=@UserName ";
            }
            //姓名
            if (dic_conditions.ContainsKey("RealName"))
            {
                dic.Add("@RealName", dic_conditions["RealName"]);
                where += " AND a.RealName=@RealName ";
            }
            //电话
            if (dic_conditions.ContainsKey("Phone"))
            {
                dic.Add("@Phone", dic_conditions["Phone"]);
                where += " AND a.Phone=@Phone ";
            }
            //邮箱
            if (dic_conditions.ContainsKey("Email"))
            {
                dic.Add("@Email", dic_conditions["Email"]);
                where += " AND a.Email=@Email ";
            }
            //
            if (dic_conditions.ContainsKey("MacAddress"))
            {
                dic.Add("@MacAddress", dic_conditions["MacAddress"]);
                where += " AND a.MacAddress=@MacAddress ";
            }
            //门店Id
            if (dic_conditions.ContainsKey("StoreId") && dic_conditions["StoreId"] != null && dic_conditions["StoreId"] != "0")
            {
                var StoreId = dic_conditions["StoreId"];
                if (dic_conditions["StoreId"].ToString().Contains(","))
                {
                    var array = dic_conditions["StoreId"].ToString().Split(',');
                    StoreId = array[array.Length - 1].ToString();
                }
                dic.Add("@StoreId", StoreId);
                where += " AND a.StoreId=@StoreId ";
            }
            //状态（1-正常；2-失效）
            if (dic_conditions.ContainsKey("Status"))
            {
                dic.Add("@Status", dic_conditions["Status"]);
                where += " AND a.Status=@Status ";
            }

            #endregion

            #region 排序

            //排序sql语句拼接
            string orderby = " Id DESC ";//默认排序
            if (!string.IsNullOrWhiteSpace(field))
            {
                orderby = string.Format("{0} {1}", field, string.IsNullOrWhiteSpace(order) ? "DESC" : order);
            }

            #endregion

            var sql = $"SELECT {select} FROM {table} WHERE {where} ";

            var list = _repository.GetDynamicPaged(pageNumber, rowsPerPage, orderby, sql, dic);

            count = _repository.RecordQueryCount(sql, dic);

            return Mapper.Map<List<dynamic>>(list);
        }

        /// <summary>
        /// 获取查询结果行数
        /// </summary>
        /// <param name="conditions"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public int GetListCount(string conditions, object param)
        {
            return _repository.RecordCount(conditions, param);
        }

        /// <summary>
        /// 根据用户名获取
        /// </summary>
        /// <param name="userName"></param>
        /// <returns></returns>
        public Teacher GetModel(string userName)
        {
            return _repository.QueryFirstOrDefault("SELECT * FROM Ser_Teacher WHERE IsDeleted=0 AND UserName=@UserName", new { UserName = userName });
        }

        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="memberId"></param>
        /// <returns></returns>
        public List<Teacher> GetList(int storeId)
        {
            var where = @" WHERE IsDeleted = 0 AND StoreId = @StoreId";
            var list = _repository.GetList(where, new { StoreId = storeId }).ToList();
            return list;
        }

        /// <summary>
        ///  判断是否存在账号
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public bool Exist(string userName, int? id)
        {
            if (id.HasValue)
            {
                var where = @" WHERE IsDeleted = 0 AND UserName = @UserName AND Id != @Id";
                var list = _repository.GetList(where, new { UserName = userName, Id = id }).ToList();
                return list.Count > 0;
            }
            {
                var where = @" WHERE IsDeleted = 0 AND UserName = @UserName ";
                var list = _repository.GetList(where, new { UserName = userName }).ToList();
                return list.Count > 0;
            }
        }

        #endregion

        #region 编辑

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int Add(TeacherInput model)
        {
            var dbtran = _repository.BeginTransaction();//开启事务
            try
            {
                var entity = Mapper.Map<Teacher>(model);
                entity.CreatorUserId = UserAuthentication.GetCurrentUser().UserID;
                entity.CreationTime = DateTime.Now;
                entity.PassWord = new Common.Symmetric().Encrypto(model.PassWord);

                int? Id = _repository.Insert(entity, dbtran);

                dbtran.Commit();//提交事务
                return 1;
            }
            catch (Exception ee)
            {
                dbtran.Rollback();//事务回滚
                throw new Exception(ee.Message);
            }
            finally
            {
                dbtran.Dispose();//释放事务资源
            }
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int Update(Teacher entity, IDbTransaction dbtran)
        {
            return _repository.Update(entity, dbtran);
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int Edit(TeacherInput model)
        {
            var dbtran = _repository.BeginTransaction();//开启事务
            try
            {
                DateTime now = DateTime.Now;

                var entity = _repository.Get(model.Id, dbtran);
                model.PassWord = entity.PassWord;
                Mapper.Map(model, entity);//把model数据转移到entity
                entity.LastModifierUserId = UserAuthentication.GetCurrentUser().UserID;
                entity.LastModificationTime = DateTime.Now;

                _repository.Update(entity, dbtran);
                dbtran.Commit();//提交事务
                return 1;
            }
            catch (Exception ee)
            {
                dbtran.Rollback();//事务回滚
                throw new Exception(ee.Message);
            }
            finally
            {
                dbtran.Dispose();//释放事务资源
            }
        }

        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="IdList"></param>
        /// <returns></returns>
        public void DeleteList(string IdList)
        {
            var dbtran = _repository.BeginTransaction();//开启事务
            try
            {
                foreach (string Id in IdList.Split(new Char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
                {
                    Teacher model = _repository.Get(Id, dbtran);
                    model.IsDeleted = true;
                    _repository.Update(model, dbtran);
                }
                dbtran.Commit();//提交事务
            }
            catch (Exception)
            {
                dbtran.Rollback();//事务回滚
            }
            finally
            {
                dbtran.Dispose();//释放事务资源
            }
        }

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="IdList"></param>
        /// <returns></returns>
        public void ResetPassWord(string IdList)
        {
            var dbtran = _repository.BeginTransaction();//开启事务
            try
            {
                foreach (string Id in IdList.Split(new Char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
                {
                    Teacher model = _repository.Get(Id, dbtran);
                    model.PassWord = new Symmetric().Encrypto("123456");
                    model.LastModifierUserId = UserAuthentication.GetCurrentUser().UserID;
                    model.LastModificationTime = DateTime.Now;
                    _repository.Update(model, dbtran);
                }
                dbtran.Commit();//提交事务
            }
            catch (Exception)
            {
                dbtran.Rollback();//事务回滚
            }
            finally
            {
                dbtran.Dispose();//释放事务资源
            }
        }

        /// <summary>
        /// 修改单个字段
        /// </summary>
        /// <param name="ID"></param>
        /// <param name="field"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public int UpdateStatus(int ID, int status)
        {
            try
            {
                Teacher model = _repository.Get(ID);
                model.Status = status;
                model.LastModificationTime = DateTime.Now;//修改时间
                model.LastModifierUserId = UserAuthentication.GetCurrentUser().UserID;//修改用户

                return _repository.Update(model);
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 更新登录时间
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public Result UpdateLoginTime(int id)
        {
            Result result = new Result() { Success = false };
            var dbtran = _repository.BeginTransaction();//开启事务
            try
            {
                var entity = _repository.Get(id, dbtran);

                entity.LastLoginTime = DateTime.Now;
                _repository.Update(entity, dbtran);

                dbtran.Commit();//提交事务
                result.Success = true;
                result.Message = "更新成功";
            }
            catch (Exception ee)
            {
                dbtran.Rollback();//事务回滚
                result.Success = false;
                result.Message = ee.Message;
            }
            finally
            {
                dbtran.Dispose();//释放事务资源
            }
            return result;
        }

        #endregion
    }
}

